package com.example.administrator.xiaoxiang.utils;


import android.os.Handler;
import android.util.Log;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.Map;


/**
 * Created by Administrator on 2017/1/3.
 */

public class OkHttpHelper {


    //单例模式
    private static OkHttpClient okHttpClient;
    private Handler mHandler;

    private OkHttpHelper() {
        okHttpClient = new OkHttpClient();
//        okHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
//        okHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
//        okHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
        mHandler = new Handler();
    }


    public static OkHttpHelper getInstance() {
        return new OkHttpHelper();
    }

    public void get(String url, BaseCallback callback) {
        Request request = bulidRequest(url, null, HttpMethodType.Get);
        doRequest(request, callback);
    }

    public void post(String url, Map<String, String> params, BaseCallback callback) {
        Request request = bulidRequest(url, params, HttpMethodType.Post);
        doRequest(request, callback);
    }


    public void doRequest(Request request, final BaseCallback callback) {
        callback.onBeforeRequest(request);

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                callback.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                callback.onResponse(response);

                if (response.isSuccessful()) {

                    String resultStr = response.body().string();

                    callbackSuccess(callback, resultStr);


                } else {
                    callbackError(callback, response, null);
                }

            }
        });


    }

    private Request bulidRequest(String url, Map<String, String> params, HttpMethodType methodType) {
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (methodType == HttpMethodType.Get) {
            builder.get();
        } else if (methodType == HttpMethodType.Post) {
            RequestBody body = buildFormData(params);
            builder.post(body);
        }
        return builder.build();
    }

    private RequestBody buildFormData(Map<String, String> params) {
        FormEncodingBuilder builder = new FormEncodingBuilder();

        if (params != null) {

            for (Map.Entry<String, String> entry : params.entrySet()) {

                builder.add(entry.getKey(), entry.getValue());
            }
        }
        return builder.build();
    }


    private void callbackSuccess(final BaseCallback callback, final String string) {

        mHandler.post(new Runnable() {
            @Override
            public void run() {

                if (string==null){
                    Log.e("CCC","CCCC数据为空");
                }else {
                    Log.e("CCC","CCCC"+string);
                    callback.onSuccess(string);
                }
            }
        });
    }


    private void callbackError(final BaseCallback callback, final Response response, final Exception e) {

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Log.e("CCC","CCCC"+response.code());
                callback.onError(response, response.code(), e);
            }
        });
    }

    enum HttpMethodType {
        Get, Post
    }
}
